/**
Copyright (c) 2011  Nicholas Zhu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package com.cardgroup.cbrp.springmem.aop;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.InvalidParameterException;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import com.cardgroup.cbrp.springmem.annotations.AnnotationConstants;
import com.cardgroup.cbrp.springmem.exceptions.InvalidAnnotationException;
/**
 * The basic builder for annotation data
 * @author nicholas
 *
 */
public class AnnotationDataBuilder implements IAnnotationDataBuilder {
	protected Class expectedAnnotationClass;
	protected JoinPoint jp;
	protected AnnotationData data;
	protected Annotation annotation;
	protected Method methodToCache;
	public AnnotationDataBuilder(final Class expectedAnnotationClass, final JoinPoint jp){
		this.expectedAnnotationClass = expectedAnnotationClass;
		this.jp = jp;
		data = new AnnotationData();
	}

	/**
	 * Build annotation data
	 * Gathering data from annotation and populating into AnnotationData
	 */
	public void buildAnnotation() throws SecurityException, NoSuchMethodException {
		// TODO Auto-generated method stub
		
		final Signature sig = jp.getSignature();
		if (!(sig instanceof MethodSignature)) {
			throw new InvalidAnnotationException(
					"This annotation is only valid on a method.");
		}
		final MethodSignature msig = (MethodSignature) sig;
		final Object target = jp.getTarget();
		String className = target.getClass().getName();
		methodToCache = target.getClass().getMethod(
				msig.getName(), msig.getParameterTypes());

		annotation = methodToCache.getAnnotation(expectedAnnotationClass);

		if (annotation == null) {
			throw new InvalidParameterException(String.format(
					"No annotation of type [%s] found.",
					expectedAnnotationClass.getName()));
		}

		final Class clazz = annotation.annotationType();
		if (!expectedAnnotationClass.equals(clazz)) {
			throw new InvalidParameterException(
					String.format(
							"No annotation of type [%s] found, class was of type [%s].",
							expectedAnnotationClass.getName(), clazz.getName()));
		}
		data.setClassName(clazz.getName());

		// get method name
		Method method = msig.getMethod();
		String methodName = method.getName();
		data.setMethod(methodName);
		
		/**
		 * get namespace
		 */
		final Method namespaceMethod = clazz.getDeclaredMethod("namespace",
				null);
		String namespace;
		try {
			namespace = (String) namespaceMethod.invoke(
					annotation, null);
		
		if (AnnotationConstants.DEFAULT_STRING.equals(namespace)
				|| namespace == null || namespace.length() < 1) {
			throw new InvalidParameterException(
					String.format(
							"Namespace for annotation [%s] must be defined on [%s]",
							expectedAnnotationClass.getName(),
							methodToCache));
		}
		data.setNamespace(namespace);
		} catch (IllegalAccessException ex) {
			throw new RuntimeException(
					"Problem assembling Annotation information.", ex);
		} catch (InvocationTargetException ex) {
			throw new RuntimeException(
					"Problem assembling Annotation information.", ex);
		}
	}

	/**
	 * Build Cache Key
	 * namespace:method:parameters
	 */
	public void buildKey() {
		StringBuilder key = new StringBuilder();
		key.append(data.getNamespace());
		key.append(SEPARATOR);
		key.append(data.getMethod());
		key.append(SEPARATOR);
		if(data.getParameters() !=null){
			key.append(data.getParameters());
		}
		data.setKey(key.toString());
		
	}

	public AnnotationData getAnnotationData() {
		// TODO Auto-generated method stub
		return data;
	}

	/**
	 * Build Group Key
	 * namespace:group
	 */
	public void buildGroupKey() {
		// TODO Auto-generated method stub
		StringBuilder groupKey = new StringBuilder();
		groupKey.append(data.getNamespace());
		groupKey.append(SEPARATOR);
		groupKey.append(data.getGroup());
		data.setGroupKey(groupKey.toString());
	}
}
